<template>
  <div class="main">
    <div class="communitys-list content-wrap">
      <div class="inner">
        <div class="row filter-container">
          <div class="select-container">
            <button class="selected-btn" @mouseover="showPanel=true">{{ selectPro.name}}
              <i class="fa fa-caret-down" aria-hidden="true"></i>
            </button>
            <div v-show="showPanel" class="select-panel" @click="selectCompany" @mouseleave="showPanel=false">
              <div class="btn-wrap">
                <button v-for="co in companys"type="button" class="select-btn" :value="co.name">{{ co.name }}</button>
              </div>
            </div>
          </div>
          <div class="search-container">
            <div class="search-box">
              <input class="search-input" id="search" placeholder="搜索" type="text" >
              <i class="search-icon"></i>
            </div>
          </div>
        </div>
        <div class="list-box-container">
          <div class="list-box">
            <div v-for="i in countedCommunitys" class="list-item-wrap">
              <router-link :to="i.path">
                <div class="item">
                  <div class="row">
                    <div class="col-12 name">
                      <span>{{ i.name }}</span>
                    </div>
                    <div class="col-12 value">
                      <div class="top row">
                        <span v-animated-number="i.value.total"></span>
                      </div>
                      <div class="bottom-icon" :style="{ width: i.value.total * 80 / max + '%' }">
                        <div class="gray" :style="{ width: (i.value.gray) * 100 / i.value.total + '%' }"></div>
                        <div class="red" :style="{ width: (i.value.red) * 100 / i.value.total + '%' }"></div>
                        <div class="yellow" :style="{ width: (i.value.yellow) * 100 / i.value.total + '%' }"></div>
                        <div class="green" :style="{ width: (i.value.green) * 100 / i.value.total + '%' }"></div>
                      </div>
                    </div>
                  </div>
                </div>
              </router-link>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="right-info content-wrap">
      <div class="community">
        <div class="title">
          社区
        </div>
        <div class="value">
          <span class="img"></span>
          <span v-animated-number="statistics.community"></span>
        </div>
      </div>
      <div class="device">
        <div class="title">
          监控设备
        </div>
        <div class="value">
          <span class="img"></span>
          <span v-animated-number="statistics.device"></span>
        </div>
      </div>
      <div class="online">
        <div class="title">
          在线
        </div>
        <div class="value">
          <span class="img"></span>
          <span v-animated-number="statistics.online"></span>
        </div>
      </div>
    </div>

    <div class="bottom-info">
      <span>设备运行健康指数：</span>
      <button type="button" class="green" @click="selectMapColor('green')">正常</button>
      <button type="button" class="yellow" @click="selectMapColor('yellow')">异常</button>
      <button type="button" class="red" @click="selectMapColor('red')">故障</button>
      <button type="button" class="gray" @click="selectMapColor('gray')">离线</button>
    </div>
    <div class="dashboard-home content-wrap">
      <div class="inner">
        <chart :options="mapOptions" :loading="loadingData" type="bmap" height="100%" width="100%"></chart>
      </div>
    </div>
  </div>
</template>

<script>
import MAP_STYLE from './map-style'
import _ from 'lodash'
// import axios from 'axios'
import coordinates from 'static/data/map/coordinates.json'
import companys from './poly-companys'
import DEVICE_TYPES from 'config/device-types'
// import api from 'api'
// import PRODUCTIDS from 'config/product-ids'
// import ELEDATA from 'static/data/devices/electric.json'
// import filters from 'filters'
// import ELEALERTDATA from 'static/data/devices/electricAlert.json'

let MAX_SYMBOL_SIZE = 80
let MIN_SYMBOL_SIZE = 8

// let CITYSTRUCTURE = {
//   '佛山': '佛山一号公馆',
//   '佛山保利花园': '佛山保利花园',
//   '武汉': '武汉保利拉菲',
//   '北京': '北京首开天誉',
//   '天津': '天津保利罗蓝公馆',
//   '重庆': '重庆保利山庄',
//   '安徽': '安徽保利拉菲公馆',
//   '浙江': '浙江保利梧桐语',
//   '湖南': '湖南保利花园',
//   '江西': '江西保利百合花园'
// }
export default {
  name: 'Dashboard',

  data () {
    return {
      geoCoordMap: {},
      loadingData: false,
      provinces: [],
      selectPro: {
        name: '广东'
      },
      showPanel: false,
      companys: companys,
      mapColor: 'green',
      id: ':0',

      cityName: ['广州保利香槟', '广州保利天悦', '佛山一号公馆', '佛山保利花园', '武汉保利拉菲', '北京首开天誉', '天津保利罗蓝公馆', '重庆保利山庄', '安徽保利拉菲公馆', '浙江保利梧桐语', '湖南保利花园', '江西保利百合花园', '武汉', '北京', '天津', '重庆', '安徽', '浙江', '湖南', '江西', '珠海', '中山', '惠州', '汕尾', '上海', '东莞', '阳江', '江门', '清远', '合肥', '北京', '重庆', '厦门', '福州', '兰州', '海口', '三亚', '石家庄', '沧州', '衡水', '洛阳', '郑州', '太原', '晋中', '青岛', '烟台', '济宁', '腾州', '包头', '沈阳', '营口', '通化', '丹东', '赣州', '吉安', '宜春', '南昌', '连云港', '无锡', '常州', '南京', '长春', '郴州', '常德', '岳阳', '长沙', '襄阳', '黄冈', '大连', '宁波', '绍兴', '杭州', '乌鲁木齐', '成都', '德阳', '遂宁', '西安']
    }
  },

  computed: {
    waterDevices () {
      return this.$store.getters.tubesHome
    },
    electricalDevices () {
      return this.$store.getters.phaseHome
    },
    phoneDevices () {
      return this.$store.getters.phonesDevices
    },
    // 天悦正常设备数量
    TIANRUInormalDevicesNum () {
      let water = _.filter(this.waterDevices, (item) => {
        return !item.isWarnning && item.type === DEVICE_TYPES.TUBE_PRESSURE && item.online && item.area === '天悦'
      })
      let electrical = _.filter(this.electricalDevices, (item) => {
        return !item.isWarnning && item.type === DEVICE_TYPES.PHASE && item.online && item.area === '天悦'
      })
      let phone = _.filter(this.phoneDevices, (item) => {
        return item.status - 0 === 1 && item.area === '天悦'
      })
      // console.log([water.length, electrical.length, phone.length])
      return water.length + electrical.length + phone.length
    },
    // 香槟正常设备数量
    XIANGBINnormalDevicesNum () {
      let water = _.filter(this.waterDevices, (item) => {
        return !item.isWarnning && item.type === DEVICE_TYPES.TUBE_PRESSURE && item.online && item.area === '香槟'
      })
      let electrical = _.filter(this.electricalDevices, (item) => {
        return !item.isWarnning && item.type === DEVICE_TYPES.PHASE && item.online && item.area === '香槟'
      })
      return water.length + electrical.length
    },
    // 天悦异常设备数量
    TIANRUIwarningDevicesNum () {
      let water = _.filter(this.waterDevices, (item) => {
        return item.isWarnning && item.type === DEVICE_TYPES.TUBE_PRESSURE && item.online && item.area === '天悦'
      })
      let electrical = _.filter(this.electricalDevices, (item) => {
        return item.isWarnning && item.type === DEVICE_TYPES.PHASE && item.online && item.area === '天悦'
      })
      return water.length + electrical.length
    },
    // 香槟异常设备数量
    XIANGBINGwawrningDevicesNum () {
      let water = _.filter(this.waterDevices, (item) => {
        return item.isWarnning && item.type === DEVICE_TYPES.TUBE_PRESSURE && item.online && item.area === '香槟'
      })
      let electrical = _.filter(this.electricalDevices, (item) => {
        return item.isWarnning && item.type === DEVICE_TYPES.PHASE && item.online && item.area === '香槟'
      })
      return water.length + electrical.length
    },
    // 天悦不在线设备数量
    TIANRUIofflineDevicesNum () {
      let onlineWater = _.filter(this.waterDevices, (item) => {
        return !item.isWarnning && item.type === DEVICE_TYPES.TUBE_PRESSURE && item.online && item.area === '天悦'
      })
      let onlineElectrical = _.filter(this.electricalDevices, (item) => {
        return !item.isWarnning && item.type === DEVICE_TYPES.PHASE && item.online && item.area === '天悦'
      })
      let onlinePhone = _.filter(this.phoneDevices, (item) => {
        return item.status - 0 === 1 && item.area === '天悦'
      })
      return 42 + this.phoneDevices.length - onlineWater.length - onlineElectrical.length - onlinePhone.length
    },
    // 香槟不在线设备数量
    XIANGBINGofflineDevicesNum () {
      let onlineWater = _.filter(this.waterDevices, (item) => {
        return !item.isWarnning && item.type === DEVICE_TYPES.TUBE_PRESSURE && item.online && item.area === '香槟'
      })
      let onlineElectrical = _.filter(this.electricalDevices, (item) => {
        return !item.isWarnning && item.type === DEVICE_TYPES.PHASE && item.online && item.area === '香槟'
      })
      return 8 - onlineWater.length - onlineElectrical.length
    },
    communitys () {
      return [{
        area: '广州',
        name: '保利 天悦',
        path: '/:0/dashboard/monitor',
        value: {
          green: this.TIANRUInormalDevicesNum,
          yellow: this.TIANRUIwarningDevicesNum,
          red: 0,
          gray: this.TIANRUIofflineDevicesNum
        }
      },
      {
        area: '广州',
        name: '保利 香槟',
        path: '/:1/dashboard/water',
        value: {
          green: this.XIANGBINnormalDevicesNum,
          yellow: this.XIANGBINGwawrningDevicesNum,
          red: 0,
          gray: this.XIANGBINGofflineDevicesNum
        }
      }]
    },
    yellowData () {
      let arr = this.cityName
      let arry = []
      arr.forEach(item => {
        let obj = {name: item, value: 0}
        if (item === '广州保利天悦') {
          obj['value'] = this.TIANRUIwarningDevicesNum
        } else if (item === '广州保利香槟') {
          obj['value'] = this.XIANGBINGwawrningDevicesNum
        }
        arry.push(obj)
      })
      return arry
    },
    redData () {
      let arr = this.cityName
      let arry = []
      arr.forEach(item => {
        let obj = {name: item, value: 0}
        if (item === '广州') {
          obj['value'] = 0
        }
        arry.push(obj)
      })
      return arry
    },
    grayData () {
      let arr = this.cityName
      let arry = []
      arr.forEach(item => {
        let obj = {name: item, value: 0}
        if (item === '广州保利天悦') {
          obj['value'] = this.TIANRUIofflineDevicesNum
        } else if (item === '广州保利香槟') {
          obj['value'] = this.XIANGBINGofflineDevicesNum
        }
        arry.push(obj)
      })
      return arry
    },
    greenData () {
      let arr = this.cityName
      let arry = []
      arr.forEach(item => {
        let obj = {name: item, value: 0}
        if (item === '广州保利天悦') {
          obj['value'] = this.TIANRUInormalDevicesNum
        } else if (item === '广州保利香槟') {
          obj['value'] = this.XIANGBINnormalDevicesNum
        }
        arry.push(obj)
      })
      return arry
    },
    assignColor () {
      let res = '#FFFF8D'
      switch (this.mapColor) {
        case 'yellow':
          res = '#FFFF8D'
          break
        case 'green':
          res = '#81C784'
          break
        case 'red':
          res = '#FF8A80'
          break
        case 'gray':
          res = '#757575'
          break
      }
      return res
    },
    cityData () {
      let res = []
      switch (this.mapColor) {
        case 'yellow':
          res = this.yellowData
          break
        case 'green':
          res = this.greenData
          break
        case 'red':
          res = this.redData
          break
        case 'gray':
          res = this.grayData
          break
      }
      return res || []
    },
    countedCommunitys () {
      return _.map(this.communitys, (item) => {
        return {
          area: item.area,
          name: item.name,
          path: item.path,
          value: {
            total: item.value.green + item.value.red + item.value.yellow + item.value.gray,
            green: item.value.green,
            yellow: item.value.yellow,
            red: item.value.red,
            gray: item.value.gray
          }
        }
      })
    },
    statistics () {
      return {
        community: this.communitys.length,
        device: _.sumBy(this.communitys, function (item) {
          return item.value.green + item.value.red + item.value.yellow + item.value.gray
        }),
        online: _.sumBy(this.communitys, function (item) {
          return item.value.green + item.value.red + item.value.yellow
        })
      }
    },
    max () {
      let totals = _.map(this.communitys, (item) => {
        return item.value.green + item.value.red + item.value.yellow + item.value.gray
      })
      return Math.max(...totals)
    },
    mapOptions () {
      let self = this
      return {
        tooltip: {
          trigger: 'item',
          formatter (params) {
            if (params.name === '广州保利天悦') {
              return `正常 : ${self.countedCommunitys[0].value.green}<br/>异常 : 0<br/>故障 : 0<br/>离线 : ${self.countedCommunitys[0].value.gray}<br/>`
            } else if (params.name === '广州保利香槟') {
              return `正常 : ${self.countedCommunitys[1].value.green}<br/>异常 : 0<br/>故障 : 0<br/>离线 : ${self.countedCommunitys[1].value.gray}<br/>`
            }
            return params.name
          }
        },
        bmap: {
          center: [105, 37.550339],
          zoom: 5,
          roam: true,
          mapStyle: {
            styleJson: MAP_STYLE // 地图样式
          }
        },
        series: [{
          name: '',
          type: 'effectScatter',
          coordinateSystem: 'bmap',
          data: this._convertData(this.cityData.slice(0, 10)),
          symbolSize (val) {
            let result

            if (self.max) {
              result = MAX_SYMBOL_SIZE * val[2] / self.max
            }

            if (result < MIN_SYMBOL_SIZE) {
              result = MIN_SYMBOL_SIZE
            }
            return 20
          },
          hoverAnimation: true,
          label: {
            normal: {
              formatter: '{b}',
              position: 'right',
              show: false
            },
            emphasis: {
              show: true
            }
          },
          itemStyle: {
            normal: {
              color: this.assignColor
            }
          },
          zlevel: 1
        }, {
          name: '',
          type: 'scatter',
          coordinateSystem: 'bmap',
          data: this._convertData(this.cityData.slice(10)),
          symbolSize (val) {
            let result

            if (self.max) {
              result = MAX_SYMBOL_SIZE * val[2] / self.max
            }

            if (result < MIN_SYMBOL_SIZE) {
              result = MIN_SYMBOL_SIZE
            }
            return result
          },
          showEffectOn: 'render',
          rippleEffect: {
            brushType: 'stroke'
          },
          hoverAnimation: true,
          label: {
            normal: {
              formatter: '{b}',
              position: 'right',
              show: false
            }
          },
          itemStyle: {
            normal: {
              color: 'gray',
              shadowBlur: 10
            }
          },
          silent: false
        }]
      }
    },
    tempHumidity () {
      if (!this.data.devices) {
        return {}
      }

      let res = _.find(this.data.devices, (item) => {
        return item.type === DEVICE_TYPES.TEMP_HUMIDITY
      })

      return res || {}
    }
  },

  mounted () {
    this.initGeoMap()
  },

  methods: {
    initGeoMap () {
      let geoCoordMap = {}
      let cities = coordinates.municipalities

      _.forEach(coordinates.provinces, (item) => {
        cities = cities.concat(item.cities)
      })
      cities = cities.concat(coordinates.other)

      _.forEach(cities, (item) => {
        let arr = item.g.split(',')
        geoCoordMap[item.n] = [arr[0], arr[1]]
      })

      geoCoordMap['佛山一号公馆'] = ['113.1663801550', '23.0267150322']
      geoCoordMap['佛山保利花园'] = ['113.1596920982', '23.0693599715']
      geoCoordMap['武汉保利拉菲'] = ['114.3793987424', '30.5038662823']
      geoCoordMap['北京首开天誉'] = ['116.5356619420', '39.9726862240']
      geoCoordMap['天津保利罗蓝公馆'] = ['117.0450860196', '39.0753504400']
      geoCoordMap['重庆保利山庄'] = ['106.5117070672', '29.5738860103']
      geoCoordMap['安徽保利拉菲公馆'] = ['117.2796071207', '31.7230925554']
      geoCoordMap['浙江保利梧桐语'] = ['120.2534986863', '30.3182351640']
      geoCoordMap['湖南保利花园'] = ['115.957716', '28.711563']
      geoCoordMap['广州保利天悦'] = ['113.3860887439', '23.1087072548']
      geoCoordMap['广州保利香槟'] = ['113.3239668446', '23.1231391273']
      this.geoCoordMap = geoCoordMap
    },
    selectMapColor (color) {
      this.mapColor = color
    },
    selectCompany (e) {
      this.showPanel = false
      this.selectPro.name = e.target.value
    },
    /**
     * 转换地图数据
     */
    _convertData (data) {
      var res = []
      for (var i = 0; i < data.length; i++) {
        var geoCoord = this.geoCoordMap[data[i].name]
        if (geoCoord) {
          res.push({
            name: data[i].name,
            value: geoCoord.concat(data[i].value)
          })
        }
      }
      return res
    }
  }
}
</script>

<style lang="stylus">
@import '../../../assets/stylus/base'
@import './index.styl'
</style>
